package com.kanshu.basictest.widget.adapter.menu;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;

import com.kanshu.basictest.model.menu.MenuItem;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatButton;
import androidx.recyclerview.widget.RecyclerView;

public class RecyclerMenuAdapter<T extends MenuItem> extends RecyclerView.Adapter<RecyclerMenuViewHolder> {

    private List<T> mMenuList;

    private OnItemClickedListener<T> onItemClickedListener;

    public RecyclerMenuAdapter(@NonNull List<T> menuItems) {
        mMenuList = menuItems;
    }


    public void setOnItemClickedListener(OnItemClickedListener<T> listener) {
        onItemClickedListener = listener;
    }


    @NonNull
    @Override
    public RecyclerMenuViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        AppCompatButton button = new AppCompatButton(parent.getContext());
        //解决焦点冲突
        button.setClickable(false);
        button.setFocusable(false);
        button.setFocusableInTouchMode(false);
        button.setAllCaps(false);

        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        button.setLayoutParams(layoutParams);
        return new RecyclerMenuViewHolder(button);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerMenuViewHolder holder, int position) {

        AppCompatButton button = (AppCompatButton) holder.itemView;
        T menuItem = mMenuList.get(position);
        button.setText(String.valueOf(position + 1).concat(".").concat(menuItem.getName()));
        button.setBackgroundResource(menuItem.getColor());

        button.setOnClickListener(v -> {
            if (onItemClickedListener != null) {
                onItemClickedListener.onItemClicked(RecyclerMenuAdapter.this, button, menuItem, position);
            }
        });


    }


    @Override
    public int getItemViewType(int position) {
        return position % 2;
    }

    @Override
    public int getItemCount() {
        return mMenuList.size();
    }


    public interface OnItemClickedListener<E> {

        void onItemClicked(RecyclerView.Adapter<?> adapter, View itemView, E item, int pos);
    }
}
